package org.lemon.transport.context.config.ssl;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.lemon.transport.context.utils.StringUtils;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;

@Data
@EqualsAndHashCode(callSuper = false)
public class KeystoreSslCredentials extends AbstractSslCredentials {

    private String type;
    private String storeFile;
    private String storePassword;
    private String keyPassword;
    private String keyAlias;

    @Override
    protected KeyStore loadKeyStore(boolean isPrivateKeyRequired, char[] keyPasswordArray) throws IOException, GeneralSecurityException {

        String keyStoreType = StringUtils.isNullOrEmpty(this.type) ? KeyStore.getDefaultType() : this.type;
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        try {
            File file = ResourceUtils.getFile(this.storeFile);
            keyStore.load(new FileInputStream(file), this.storePassword.toCharArray());
        } catch (FileNotFoundException e) {
            throw new RuntimeException("Unable to find resource: " + this.storeFile);
        }
        return keyStore;
    }

    @Override
    public String getKeyPassword() {
        return this.keyPassword;
    }

    @Override
    public String getKeyAlias() {
        return this.keyAlias;
    }
}
